package com.example.javaserve.user;

import com.example.javaserve.entity.SysUser;
import com.example.javaserve.entity.UserBaseInfo;
import com.example.javaserve.service.SysUserService;
import com.example.javaserve.service.UserBaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @projectName: my_project
 * @package: com.example.javaserve.user
 * @className: UserDetailServiceInfoImpl
 * @author: xxXPCSC
 * @description: TODO
 * @date: 2023/11/17 15:46
 * @version: 1.0
 **/
@Service
public class UserDetailServiceInfoImpl implements UserDetailsService {
    @Autowired
    private UserBaseInfoService userBaseInfoService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserBaseInfo userBaseInfo = userBaseInfoService.getByUsername(username);
        if (userBaseInfo == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }


        return new AccountUser(userBaseInfo.getInfoUsername(), userBaseInfo.getInfoPassword(), getUserAuthority(userBaseInfo.getInfoUsername()));

    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     * @param
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(String username) {
        // 实际怎么写以数据表结构为准，这里只是写个例子
        // 角色(比如ROLE_admin)，菜单操作权限(比如sys:user:list)
        String authority = userBaseInfoService.getUserRoleInfo(username);     // 比如ROLE_admin,ROLE_normal,sys:user:list,...

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
